package pc

import (
	. "chess_platform/internal/common"
	"fmt"
	"github.com/astaxie/beego/orm"
)

//反馈方面的
func UpdateFeedbackStatus(data map[string]interface{}, id, typ int64) (int64, error) {
	o := orm.NewOrm()
	//类型,1-h5用户反馈,2-游戏用户反馈
	condition := fmt.Sprintf(`id = %v`, id)
	table := ""
	if typ == 1 {
		o.Using(DBChessCenter)
		table = TableH5Feedback
	} else {
		o.Using(DBChess)
		table = TableFeedback
	}
	values, sql := UpdateSql(table, data, condition)
	result, err := o.Raw(sql, values).Exec()
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

func ListFeedback(p ListParams, typ int64) ([]orm.Params, int64, error) {
	if typ == 1 {
		return listH5Feedback(p)
	}
	return listClientFeedback(p)
}

func listH5Feedback(p ListParams) ([]orm.Params, int64, error) {
	limit := (p.PageIndex - 1) * p.PageSize
	sql := fmt.Sprintf(`
		SELECT
			f.*, u.nickname,u.phone
		FROM
			%v AS f
		LEFT JOIN
			%v AS u
		ON f.uid = u.uid
		ORDER BY
			f.id DESC
		LIMIT ?,?
		`, TableH5Feedback, TableH5User)
	o := NewDBOrm(DBChessCenter)
	var gl []orm.Params
	_, err := o.Raw(sql, limit, p.PageSize).Values(&gl)
	if CheckNoExist(err) {
		return nil, 0, nil
	}

	//查找图片
	sql = fmt.Sprintf(`
		SELECT
			url
		FROM
			%v
		WHERE
			fid = ?
	`, TableH5FeedbackUrl)
	for _, v := range gl {
		var url []string
		o.Raw(sql, v["id"]).QueryRows(&url)
		v["url"] = url
		v["operator_name"] = UserNameById(v["operator_id"])
	}

	sql = fmt.Sprintf(`SELECT COUNT(1) FROM %v `, TableH5Feedback)
	var count int64
	err = o.Raw(sql).QueryRow(&count)
	return gl, count, err
}

func listClientFeedback(p ListParams) ([]orm.Params, int64, error) {
	limit := (p.PageIndex - 1) * p.PageSize
	sql := fmt.Sprintf(`
		SELECT
			f.*, u.nickname,u.phone
		FROM
			%v AS f
		LEFT JOIN
			%v AS u
		ON f.uid = u.uid
		ORDER BY
			f.id DESC
		LIMIT ?,?
		`, TableFeedback, TableClientUser)
	o := NewDBOrm(DBChessCenter)
	var gl []orm.Params
	_, err := o.Raw(sql, limit, p.PageSize).Values(&gl)
	if CheckNoExist(err) {
		return nil, 0, nil
	}

	//查找图片
	sql = fmt.Sprintf(`
		SELECT
			url
		FROM
			%v
		WHERE
			fid = ?
	`, TableFeedbackUrl)
	var url []string
	for _, v := range gl {
		o.Raw(sql, v["id"]).QueryRows(&url)
		v["url"] = url
		v["operator_name"] = UserNameById(v["operator_id"])
	}
	sql = fmt.Sprintf(`SELECT COUNT(1) FROM %v `, TableH5Feedback)
	var count int64
	err = o.Raw(sql).QueryRow(&count)
	return gl, count, err
}
